import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:delivery_application/common_widget/round_button.dart';
import 'package:delivery_application/common_widget/round_textfield.dart';
import 'package:delivery_application/view/login/rest_password_view.dart';
import 'package:delivery_application/view/login/sign_up_view.dart';
import 'package:delivery_application/view/home/pay.dart';
import 'package:delivery_application/view/home/map_picker_view.dart';
import 'package:delivery_application/model/order_model.dart';
import 'package:delivery_application/view/login/login_view.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController txtordernumber = TextEditingController();
  TextEditingController txtaddress = TextEditingController();
  
  // 保存选择的位置坐标
  double? _selectedLat;
  double? _selectedLng;
  bool _locationSelected = false;
  String _userName = '';

  @override
  void initState() {
    super.initState();
    // 初始化时清空坐标信息
    _selectedLat = null;
    _selectedLng = null;
    _locationSelected = false;
    // 加载用户名
    _loadUserName();
  }
  
  Future<void> _loadUserName() async {
    final prefs = await SharedPreferences.getInstance();
    final userName = prefs.getString('userName') ?? '';
    
    setState(() {
      _userName = userName;
    });
  }

  Future<void> _saveOrder() async {
    if (txtordernumber.text.isEmpty || txtaddress.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请填写完整信息')),
      );
      return;
    }

    final prefs = await SharedPreferences.getInstance();
    final orders = prefs.getStringList('orders') ?? [];
    
    final newOrder = Order(
      orderNumber: txtordernumber.text,
      address: txtaddress.text,
      createTime: DateTime.now(),
      latitude: _selectedLat,
      longitude: _selectedLng,
    );

    orders.add(jsonEncode(newOrder.toJson()));
    await prefs.setStringList('orders', orders);

    print("保存订单: 地址=${txtaddress.text}, 坐标=(${_selectedLat}, ${_selectedLng})");
  }

  Future<void> _pickLocation() async {
    print("正在打开地图选择位置...");
    final result = await Navigator.push<Map<String, dynamic>>(
      context,
      MaterialPageRoute(
        builder: (context) => const MapPickerView(),
      ),
    );
    
    if (result != null && mounted) {
      setState(() {
        _selectedLat = result['latitude'];
        _selectedLng = result['longitude'];
        txtaddress.text = result['address'];
        _locationSelected = true;
      });
      print("已选择位置: ${txtaddress.text}, 坐标=(${_selectedLat}, ${_selectedLng})");
    }
  }

  @override
  Widget build(BuildContext context) {
    var media = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Color(0xff00AEEE),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 25),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(height: 30),
              Image.asset(
                "assets/img/personalaccount.png",
                width: media.width * 0.5,
                height: media.height * 0.2,
                fit: BoxFit.contain,
              ),
              SizedBox(height: 40),
              RoundTextfield(
                hintText: "请输入快递单号",
                controller: txtordernumber,
                keyboardType: TextInputType.text,
              ),
              SizedBox(height: 40),
              
              // 地址输入区域
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 10, bottom: 8),
                    child: Row(
                      children: [
                        Icon(Icons.location_on, color: Colors.white, size: 16),
                        SizedBox(width: 5),
                        Text(
                          "收货地址",
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        Spacer(),
                        // 地图选择按钮
                        GestureDetector(
                          onTap: _pickLocation,
                          child: Container(
                            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 5),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(Icons.map, color: Color(0xff00AEEE), size: 16),
                                SizedBox(width: 5),
                                Text(
                                  "打开地图",
                                  style: TextStyle(
                                    color: Color(0xff00AEEE),
                                    fontWeight: FontWeight.bold,
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Stack(
                    children: [
                      RoundTextfield(
                        hintText: "请输入您的住址或点击右侧地图按钮选择",
                        controller: txtaddress,
                        obscureText: false,
                        suffixIcon: IconButton(
                          icon: Icon(
                            Icons.location_on,
                            color: _locationSelected ? Colors.green : Colors.white,
                            size: 28,
                          ),
                          onPressed: _pickLocation,
                        ),
                      ),
                    ],
                  ),
                  
                  // 显示选择的坐标信息
                  if (_locationSelected && _selectedLat != null && _selectedLng != null)
                    Padding(
                      padding: const EdgeInsets.only(left: 10, top: 8),
                      child: Text(
                        "位置已选择: (${_selectedLat!.toStringAsFixed(4)}, ${_selectedLng!.toStringAsFixed(4)})",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    ),
                ],
              ),
              
              SizedBox(height: 40),
              RoundButton(
                title: "确认订单",
                onPressed: () async {
                  await _saveOrder();
                  print("准备跳转到支付页面，坐标：${_selectedLat}, ${_selectedLng}");
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => PayView(
                        latitude: _selectedLat,
                        longitude: _selectedLng,
                      ),
                    ),
                  );
                },
              ),
              SizedBox(height: 10),
              Image.asset(
                "assets/img/uavlogo.png",
                width: media.width * 0.5,
                height: media.height * 0.25,
                fit: BoxFit.contain,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
